﻿var access_token;
var prev_access_token, cur_access_token;
window.FB = FBWinJS;
var share = false;

/*Enter your app-id from facebook for your app here.*/
FB.options({
    appId: 'xxxxxxxxxxxxxxxxxxx'
});


(function () {
    "use strict";
    var currentApp = Windows.ApplicationModel.Store.CurrentAppSimulator;
    var page = WinJS.UI.Pages.define("/html/PointsThroughShare.html", {
        ready: function (element, options) {
            /*The code in ready function goes into the block of your app.load() function */
            document.getElementById("share2PurchaseButton").addEventListener("click", shareProduct2, false);
        },
        unload: function () {
            /*The code in unload function goes into the block of your app.unload() function */
            
        }
    });
    

    //fb stuff
    // UTILITIES

    // For logging responses
    function logResponse(response) {
        if (typeof console !== 'undefined')
            console.log('The response was', response);
    }

    // AUTHENTICATION
    function loginClicked() {

        if (access_token) { postClicked(); }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins photo_upload share_item', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {

                        access_token = result.access_token;
                        

                        postClicked();


                    }
                }
            });
        }
    }

    function postClicked() {

        FB.setAccessToken(access_token);

        var body = 'I like this app';
        FB.api('me/feed', 'post', {
            message: body, link: "", caption: "Lets Play TicTac", name: "TicTac", picture: "http://ts2.mm.bing.net/th?id=H.4528524587173721&w=194&h=184&c=7&rs=1&pid=1.7"
        }, function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                WinJS.log && WinJS.log("Unable to update points, share failed.", "sample", "error");
                return;
            }
            console.log('Post Id: ' + res.id);
            WinJS.log && WinJS.log("Thank You for sharing about the app.", "sample", "error");
            share = true;


            if (share === true && cur_access_token == prev_access_token) {
                var a = document.getElementById("points").innerText;
                var b = parseInt(a);
                b = b + 1;
                document.getElementById("points").innerText = b;
                share = false;
            }
            else {
                WinJS.log && WinJS.log("Unable to update points, share failed.", "sample", "error");
            }
        });



    }

    function askForPermissions(scope, callback) {

        var redirectUri = 'https://www.facebook.com/connect/login_success.html',
            loginUrl = FB.getLoginUrl({ scope: scope });

        try {

            Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
                Windows.Security.Authentication.Web.WebAuthenticationBroker.default,
                new Windows.Foundation.Uri(loginUrl),
                new Windows.Foundation.Uri(redirectUri))
                .then(function success(result) {
                    if (result.responseStatus == 2) {
                        console.log('error: ' + result.responseerrordetail);
                        callback(new Error(result.responseerrordetail));
                        return;
                    }

                    var parser = document.createElement('a');
                    parser.href = result.responseData;

                    var qs = extractQuerystring(parser.hash.substr(1).split('&'));

                    if (qs.error) {
                        // most likely user clicked don't allow
                        console.log('error: ' + qs.error + ' : ' + qs.error_description);
                        return;
                    }
                    // set it as the default access token.
                    FB.setAccessToken(qs.access_token);

                    callback(null, qs);

                }, function error(err) {
                    console.log('Error Number: ' + err.number);
                    console.log('Error Message: ' + err.message);
                    callback(new Error(err.message));
                });

        } catch (e) {
            // error launching web auth
            console.log(e);
        }
    }

    function extractQuerystring(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p = a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    }


    // Handle status changes
    function handleStatusChange(response) {
        if (response.authResponse) {
            logResponse(response);
            window.location.hash = '#menu';
            updateUserInfo(response);
        } else {
            window.location.hash = '#login';
        }
    }

    function updateUserInfo(response) {
        FB.api('/me',
          { fields: "name,first_name,picture" },
          function (response) {
              logResponse(response);
              var output = '';
              output += '<img src="' + response.picture.data.url + '" width="25" height="25"></img>';
              output += ' ' + response.first_name;
              $('#user-identity').html(output);
          });
    }
    function shareProduct2() {

        loginClicked();
    }         

})();